package com.ruoyi.forum.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.forum.api.vo.ReplyItem;
import com.ruoyi.forum.api.vo.TopicItem;
import com.ruoyi.forum.constant.TopicTopStatusEnum;
import com.ruoyi.forum.dao.CircleTopicDao;
import com.ruoyi.forum.dao.CircleTopicReplyDao;
import com.ruoyi.forum.domain.CircleLabel;
import com.ruoyi.forum.domain.CircleTopic;
import com.ruoyi.forum.domain.CircleTopicReply;
import com.ruoyi.forum.exception.BizExceptionEnum;
import com.ruoyi.forum.model.UnReadResult;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * service
 *
 * @author lxk
 * @date 2018-10-17 10:04:58
 */
@Service("circleTopicService")
public class CircleTopicService {

    @Autowired
    private CircleTopicDao circleTopicDao;

    @Autowired
    private CircleTopicReplyDao circleTopicReplyDao;
    @Autowired
    private DozerBeanMapper mapper;
    @Autowired
    private CircleLabelService circleLabelService;
    @Autowired
    private CircleTopicReplyService circleTopicReplyService;


    @Transactional(rollbackFor = Exception.class)
    public void great(CircleTopic circleTopic, CircleTopicReply reply) {
        circleTopicDao.save(circleTopic);
        circleTopicReplyDao.save(reply);
    }

    @Transactional(rollbackFor = Exception.class)
    public void ungreat(CircleTopic circleTopic, CircleTopicReply reply) {
        circleTopicDao.save(circleTopic);
        circleTopicReplyDao.save(reply);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(CircleTopic circleTopic, CircleTopicReply reply) {
        circleTopicDao.save(circleTopic);
        circleTopicReplyDao.save(reply);
    }

    public List<CircleTopic> getTopicOfMe(Integer pageNo, Integer rows, String uid) {
        return circleTopicDao.getTopicOfMe(pageNo, rows, uid);
    }

    public long getTopicOfMeCount(String uid) {
        return circleTopicDao.getTopicOfMeCount(uid);
    }

    /**
     * 获取未删除的帖子
     *
     * @param topicId
     * @return
     */
    public CircleTopic exist(Long topicId) throws Exception {
        CircleTopic circleTopic = circleTopicDao.getById(topicId);
        if (circleTopic == null || circleTopic.getDelFlag() == 1) {
            throw new Exception(BizExceptionEnum.CIRCLE_TOPIC_NOT_EXIST.getMessage());
        }
        return circleTopic;
    }

    /**
     * 置顶帖子
     *
     * @param topic
     */
    public void topTopic(CircleTopic topic, Integer topFlag) {
        if (TopicTopStatusEnum.TOP.value().equals(topFlag)) {
            topic.setTopTime(System.currentTimeMillis());
        } else {
            topic.setTopTime(null);
        }
        topic.setTopStatus(topFlag);
        circleTopicDao.updateById(topic);
    }

    /**
     * 新增帖子
     *
     * @param uid
     * @param content
     * @param imgs
     * @param circleLabel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addTopic(String uid, String content, String imgs, CircleLabel circleLabel) {
        CircleTopic circleTopic = new CircleTopic();
        circleTopic.setUid(uid);
        circleTopic.setContent(content);
        circleTopic.setImgs(imgs);
        circleTopic.setCreateTime(System.currentTimeMillis());
        circleTopic.setDelFlag(0);
        circleTopic.setReplyNum(0);
        circleTopic.setGreatNum(0);
        circleTopic.setLableId(circleLabel.getId());
        circleTopic.setLableName(circleLabel.getName());
        circleTopic.setReportNum(0);
        circleTopic.setTopStatus(TopicTopStatusEnum.UNTOP.value());
        circleTopicDao.save(circleTopic);

        return null;
    }

    /**
     * 根据版块id统计置顶数量
     *
     * @param lableId
     * @return
     */
    public long countTopByLabelId(String lableId) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopic::getLableId, lableId)
                .eq(CircleTopic::getDelFlag, 0)
                .eq(CircleTopic::getTopStatus, TopicTopStatusEnum.TOP.value());
        // 执行计数查询
        return circleTopicDao.count(wrapper);
    }

    public List<TopicItem> getTopicUnreadListSearch(Set<String> uidSet, String uid, Long startTime, Long endTime, int pageSize, int first) {

        List<UnReadResult> topicUnreadListSearch = circleTopicDao.getTopicUnreadListSearch(uid, startTime, endTime, pageSize, first);
        List<TopicItem> topicItems = new ArrayList<>();
        if (!CollectionUtils.isEmpty(topicUnreadListSearch)) {
            for (UnReadResult unreadListSearch : topicUnreadListSearch) {
                CircleTopic circleTopic = unreadListSearch.getTopic();
                TopicItem map = mapper.map(circleTopic, TopicItem.class);
                uidSet.add(circleTopic.getUid());
                CircleLabel circleLabel = circleLabelService.selectById(circleTopic.getLableId());
                map.setLabel(circleLabel.getName());
                CircleTopicReply circleTopicReply = unreadListSearch.getReply();
                ReplyItem replyItem = mapper.map(circleTopicReply, ReplyItem.class);
                List<ReplyItem> replyItems = new ArrayList<>();
                replyItems.add(replyItem);
                map.setReplyItemList(replyItems);
                uidSet.add(circleTopicReply.getUid());
                if (!StringUtils.isEmpty(circleTopicReply.getReplyTo())) {
                    uidSet.add(circleTopicReply.getReplyTo());
                }
                replyItem.setReplyTime(circleTopicReply.getCreateTime());
                map.setGreatStatus(circleTopicReplyService.getGreatStatus(uid, map.getId()));
                topicItems.add(map);
            }
        }

        return topicItems;
    }


    public CircleTopic getById(Long id) {
        return circleTopicDao.getById(id);
    }

    public void update(CircleTopic circleTopic) {
        circleTopicDao.updateById(circleTopic);
    }

    public List<CircleTopic> listTopTopic(LambdaQueryWrapper<CircleTopic> wrapper) {
        return circleTopicDao.list(wrapper);
    }

    public IPage<CircleTopic> page(Page<CircleTopic> topicPage, LambdaQueryWrapper<CircleTopic> wrapper) {
        return circleTopicDao.page(topicPage, wrapper);
    }
}